﻿using System;
using System.Runtime.InteropServices;
using System.Security;

namespace SilverlightViewport.Common.Interop
{
    public class RenderTargetBitmap : AlmostUnknown
    {
        [SuppressUnmanagedCodeSecurity]
        private delegate int RenderDelegate(IntPtr pStruct, IntPtr pElement, [In, Out, MarshalAs(UnmanagedType.Struct)]ref RECT prcDirtyRect);
        private RenderDelegate m_render;

        public RenderTargetBitmap(IntPtr pStruct) : base(pStruct)
        {
            SetupRenderTargetBitmapMethods();
        }

        private void SetupRenderTargetBitmapMethods()
        {
            /* Read the COM v-table pointer */
            IntPtr pVtable = Marshal.ReadIntPtr(StructPointer);

            const int RENDER_VTABLE_INDEX = 2;

            /* Get the function pointer */
            IntPtr pFunc = Marshal.ReadIntPtr(pVtable, RENDER_VTABLE_INDEX * IntPtr.Size);

            /* Cast the function pointer to a .NET delegate */
            m_render = (RenderDelegate)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(RenderDelegate));
        }

        public int Render(IntPtr pElement, ref RECT prcDirtyRect)
        {
            return m_render(StructPointer, pElement, ref prcDirtyRect);
        }
    }
}
